'use client';

import React, { useEffect, useMemo, useState } from "react";
import { usePathname } from "next/navigation";

export default function CommonComments({ lang }) {
  const pathname = usePathname();
  const [comments, setComments] = useState([]);
  const [content, setContent] = useState("");
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const base = useMemo(() => `/${lang}`, [lang]);

  async function refreshUser() {
    const res = await fetch(`${base}/api/auth/me`, { cache: "no-store" });
    const data = await res.json();
    setUser(data.user);
  }

  async function loadComments() {
    const res = await fetch(`${base}/api/comments?pathname=${encodeURIComponent(pathname)}`, { cache: "no-store" });
    const data = await res.json();
    setComments(data.comments || []);
  }

  useEffect(() => {
    let mounted = true;
    (async () => {
      setLoading(true);
      await Promise.all([refreshUser(), loadComments()]);
      if (mounted) setLoading(false);
    })();
    return () => { mounted = false; };
  }, [pathname]);

  async function submitComment(e) {
    e.preventDefault();
    if (!content.trim()) return;
    const res = await fetch(`${base}/api/comments`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ pathname, content }),
    });
    if (res.ok) {
      setContent("");
      await loadComments();
    }
  }

  return (
    <div className="mt-8">
      <h3 className="text-lg font-semibold mb-3">评论</h3>

      {loading ? (
        <div className="text-sm text-gray-500">加载中...</div>
      ) : (
        <div className="space-y-4">
          {comments.length === 0 ? (
            <div className="text-sm text-gray-500">还没有评论，快来抢沙发~</div>
          ) : (
            comments.map((c) => (
              <div key={c.id} className="border rounded p-3">
                <div className="text-sm text-gray-700 whitespace-pre-wrap">{c.content}</div>
                <div className="mt-2 text-xs text-gray-500">
                  {c.user?.displayName || c.user?.email || "匿名"} · {new Date(c.createdAt).toLocaleString()}
                </div>
              </div>
            ))
          )}
        </div>
      )}

      <div className="mt-6">
        {user ? (
          <form onSubmit={submitComment} className="space-y-2">
            <textarea
              value={content}
              onChange={(e) => setContent(e.target.value)}
              className="w-full border rounded p-2 min-h-[90px]"
              placeholder="写下你的看法..."
            />
            <div className="text-right">
              <button type="submit" className="px-3 py-1.5 bg-blue-600 text-white rounded disabled:opacity-50" disabled={!content.trim()}>
                发表
              </button>
            </div>
          </form>
        ) : (
          <div className="text-sm text-gray-600">
            请先登录本地账号后再评论。
            <a className="text-blue-600 hover:underline ml-2" href={`${base}/account`}>
              去登录
            </a>
          </div>
        )}
      </div>
    </div>
  );
}